<template>
  <div class="result">
    <van-nav-bar
      fixed
      :title="keyword + '的搜索结果'"
      left-arrow
      @click-left="$router.go(-1)"
    />
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <van-cell v-for="item in list" :key="item.art_id.toString()" :title="item.title"  @click="$router.push(`/article/${item.art_id.toString()}`)" />
    </van-list>
  </div>
</template>

<script>
import { getSearchResults } from '@/api/search'
export default {
  name: 'result',
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      page: 1
    }
  },
  computed: {
    keyword () {
      return this.$route.query.keyword
    }
  },
  methods: {
    async onLoad () {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      const res = await getSearchResults(this.keyword, this.page)
      // console.log(res)
      // 追加
      this.list = [...this.list, ...res.data.results]
      // 加载状态结束
      this.loading = false
      // 页码数要自增，不然一直都是第一页，key也会重复，会报错
      this.page++
      // 数据全部加载完成 判断条件，大于40条或者没有数据就返回没有更多数据了
      if (this.list.length >= 40 || res.data.results.length === 0) {
        this.finished = true
      }
    }
  }
}
</script>

<style lang='less' scoped>
.result {
  padding-top: 46px;
}
</style>
